package com.lagou.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName: XmlConfigBuilder
 * @Auther: Jerry
 * @Date: 2020/6/19 23:50
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class XmlConfigBuilder {

    public Configuration configuration;

    public XmlConfigBuilder(){
        this.configuration = new Configuration();
    }

    public Configuration parse(InputStream in) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(in);
        Element root = document.getRootElement();
        List<Element> list = root.selectNodes("//property");
        Properties properties = new Properties();

        // configuration解析
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            // 将属性存放到properties中
            properties.setProperty(name, value);
        }

//        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
//        comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
//        comboPooledDataSource.setUser(properties.getProperty("username"));
//        comboPooledDataSource.setPassword(properties.getProperty("password"));
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driverClass"));
        dataSource.setUrl(properties.getProperty("url"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(dataSource);

        // mapper解析
        List<Element> mapperList = root.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperPath);
        }

        return configuration;
    }
}
